<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>SharedWorker Page 1</title>
    <style>
      * {
        font-size: 28px;
      }
    </style>
  </head>
  <body>
    <h3>Page 1</h3>
    <section style="margin-top: 50px; text-align: center">
      <input id="inputMessage" value="测试消息" />
      <input type="button" value="发送消息" id="btnSend" />
      <section id="messages">
        <p>收到的消息：</p>
      </section>
    </section>

    <script src="./worker.js"></script>
    <script>
      let messagesEle = document.getElementById("messages");
      let messageEl = document.getElementById("inputMessage");
      let btnSend = document.getElementById("btnSend");
      //

      if (!window.SharedWorker) {
        alert("浏览器不支持SharedWorkder!");
      } else {
        let myWorker = new SharedWorker("./worker.js");

        myWorker.port.onmessage = function (e) {
          let msgEl = document.createElement("p");
          let data = e.data;
          msgEl.innerText = data.date + " " + data.from + ":" + data.message;
          messagesEle.appendChild(msgEl);
        };

        btnSend.addEventListener("click", function () {
          let message = messageEl.value;

          myWorker.port.postMessage({
            date: new Date().toLocaleString(),
            message,
            from: "page 1",
          });
        });

        myWorker.port.start();
      }
    </script>
  </body>
</html>
